package com.webserver.core;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 当前类用于完成请求处理的环节
 */
public class DispatcherServlet {
    public void service(HttpServletRequest request, HttpServletResponse response) {
        String path = request.getRequestURI();
        //首先判断该请求是否为请求某个业务
        try {
            HandlerMapping.MethodMapping mm = HandlerMapping.getMethod(path);
            if(mm!=null){
                Method method = mm.getMethod();
                Object controller = mm.getController();
                //调用该Controller的对应方法后接受方法返回值
                Object returnValue = method.invoke(controller,request,response);
                /*
                    返回值会有两种情况
                    如果调用的方法返回值类型为void,那么返回值为null

                 */
                Class returnType = method.getReturnType();
                //判断是否为void
                path = returnType == void.class ? null:returnValue.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            //给浏览器响应一个500错误，告知由于服务端处理错误导致请求处理失败
            File file = new File("./webapps/root/500.html");
            response.setStatusCode(500);
            response.setStatusReason("Internal Server Error");
            response.setEntity(file);
            return;
        }
        if (path!=null) {
            File file = new File("./webapps" + path);
            if (file.isFile()) {//file表示的是一个文件
                response.setEntity(file);
            } else {
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File("./webapps/root/404.html");
                response.setEntity(file);
            }
        }
        //添加一个额外的响应头
        //Server头是用来告知浏览器服务端的信息
        response.addHeader("Server","WebServer");
    }
}
